package com.hunter.common.util.document;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxml4j.document.wordprocessing.ParagraphAlignment;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule;


public class HwpfTest {

	public static void main(String[] args) {
		testWrite();
	}
	
	public static void testWrite(){
		Map<String,String> map = new HashMap<String,String>();
		map.put("${aaa}","好好好好好啊");
		String templatePath = "C:\\Users\\admin\\Desktop\\1.docx";

		try {
			// 获得XWPFDocument对象
//			XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(templatePath));
			XWPFDocument document = new XWPFDocument(new FileInputStream(templatePath));
			// 替换段落中的指定文字
			Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
			while (itPara.hasNext()) {
				XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
//				String s = paragraph.getText();
//				for (Map.Entry<String, String> entry : map.entrySet()) {
//					s = s.replace(entry.getKey(),entry.getValue());
//				}
//				XWPFRun r1 = paragraph.createRun();
//				r1.setText(s,0);
				List<XWPFRun> runs = paragraph.getRuns();
				for (XWPFRun run : runs) {
					String oneparaString = run.getText(run.getTextPosition());
					for (Map.Entry<String, String> entry : map.entrySet()) {
						oneparaString = oneparaString.replace(entry.getKey(),entry.getValue());
					}
					run.setText(oneparaString, 0);
//					if(oneparaString.startsWith("S"))
//						run.setText("S${aaa}", 0);
				}
			}

			// 替换表格中的指定文字
			Iterator<XWPFTable> itTable = document.getTablesIterator();
			while (itTable.hasNext()) {
				XWPFTable table = (XWPFTable) itTable.next();
				int rcount = table.getNumberOfRows();
				for (int i = 0; i < rcount; i++) {
					XWPFTableRow row = table.getRow(i);
					List<XWPFTableCell> cells = row.getTableCells();
					for (XWPFTableCell cell : cells) {
						String cellTextString = cell.getText();
						for (Entry<String, String> e : map.entrySet()) {
							if (cellTextString.contains(e.getKey()))
								cellTextString = cellTextString.replace(e.getKey(), e.getValue());
						}
						cell.removeParagraph(0);
						cell.setText(cellTextString);
					}
				}
			}
			XWPFParagraph p = document.createParagraph();
//			document.createParagraph().;
			String blipId = p.getDocument().addPictureData(new FileInputStream(new File("C:\\Users\\admin\\Desktop\\11.jpg")), Document.PICTURE_TYPE_JPEG);
			createPicture(blipId, document.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG), 200, 200, p);
			 p.createRun().setText("   ");
//			String blipId1 = p.getDocument().addPictureData(new FileInputStream(new File("C:\\Users\\admin\\Desktop\\11.jpg")), Document.PICTURE_TYPE_JPEG);
			
			FileOutputStream outStream = null;
			outStream = new FileOutputStream("C:\\Users\\admin\\Desktop\\2.docx");
			document.write(outStream);
			outStream.close();
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void createPicture(String blipId, int id, int width, int height,
			XWPFParagraph paragraph) {
		final int EMU = 9525;
		width *= EMU;
		height *= EMU;
		// String blipId =
		// getAllPictures().get(id).getPackageRelationship().getId();
//		if (paragraph == null) {
//			paragraph = createParagraph();
//		}
		CTInline inline = paragraph.createRun().getCTR().addNewDrawing()
				.addNewInline();
		String picXml = ""
				+ "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
				+ "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
				+ "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
				+ "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
				+ id
				+ "\" name=\"img_"
				+ id
				+ "\"/>"
				+ "            <pic:cNvPicPr/>"
				+ "         </pic:nvPicPr>"
				+ "         <pic:blipFill>"
				+ "            <a:blip r:embed=\""
				+ blipId
				+ "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
				+ "            <a:stretch>"
				+ "               <a:fillRect/>"
				+ "            </a:stretch>"
				+ "         </pic:blipFill>"
				+ "         <pic:spPr>"
				+ "            <a:xfrm>"
				+ "               <a:off x=\"0\" y=\"0\"/>"
				+ "               <a:ext cx=\""
				+ width
				+ "\" cy=\""
				+ height
				+ "\"/>"
				+ "            </a:xfrm>"
				+ "            <a:prstGeom prst=\"rect\">"
				+ "               <a:avLst/>"
				+ "            </a:prstGeom>"
				+ "         </pic:spPr>"
				+ "      </pic:pic>"
				+ "   </a:graphicData>" + "</a:graphic>";
		// CTGraphicalObjectData graphicData =
		// inline.addNewGraphic().addNewGraphicData();
		XmlToken xmlToken = null;
		try {
			xmlToken = XmlToken.Factory.parse(picXml);
		} catch (XmlException xe) {
			xe.printStackTrace();
		}
		inline.set(xmlToken);
		// graphicData.set(xmlToken);
		inline.setDistT(0);
		inline.setDistB(0);
		inline.setDistL(0);
		inline.setDistR(0);
		CTPositiveSize2D extent = inline.addNewExtent();
		extent.setCx(width);
		extent.setCy(height);
		CTNonVisualDrawingProps docPr = inline.addNewDocPr();
		docPr.setId(id);
		docPr.setName("docx_img_ " + id);
		docPr.setDescr("docx Picture");
	}
	/**
	 * 关闭输入流
	 * 
	 * @param is
	 */
	private void closeStream(InputStream is) {
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 关闭输出流
	 * 
	 * @param os
	 */
	private void closeStream(OutputStream os) {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	// 测试带图片段落
//	public void testCreateParagraphWithImg(CustomXWPFDocument_S_9 xdoc) throws Exception {
//		XWPFParagraph p = xdoc.createParagraph();
//		setParagraphAlignInfo(p, ParagraphAlignment.LEFT, TextAlignment.CENTER);
//		setParagraphSpacingInfo(p, true, "0", "0", "0", "0", true, "240",
//				STLineSpacingRule.AUTO);
//		XWPFRun pRun = getOrAddParagraphFirstRun(p, false, false);
//		setParagraphRunFontInfo(p, pRun, "1.下列实验操作中，正确的是(    ) ", "宋体", "22");
//		pRun = getOrAddParagraphFirstRun(p, true, true);
//		setParagraphRunFontInfo(p, pRun, "A", "宋体", "22");
//		String blipId = p.getDocument().addPictureData(
//				new FileInputStream(new File("f:/saveFile/temp/image1.png")),
//				Document.PICTURE_TYPE_PNG);
//		xdoc.createPicture(blipId,
//				xdoc.getNextPicNameNumber(Document.PICTURE_TYPE_PNG), 90, 93, p);
//		pRun = getOrAddParagraphFirstRun(p, true, false);
//		setParagraphRunFontInfo(p, pRun, StringUtils.leftPad("B.", 10), "宋体",
//				"22");
//		blipId = p.getDocument().addPictureData(
//				new FileInputStream(new File("f:/saveFile/temp/image2.png")),
//				Document.PICTURE_TYPE_PNG);
//		xdoc.createPicture(blipId,
//				xdoc.getNextPicNameNumber(Document.PICTURE_TYPE_PNG), 90, 93, p);
//		pRun = getOrAddParagraphFirstRun(p, true, true);
//		setParagraphRunFontInfo(p, pRun, "C", "宋体", "22");
//		blipId = p.getDocument().addPictureData(
//				new FileInputStream(new File("f:/saveFile/temp/image3.png")),
//				Document.PICTURE_TYPE_PNG);
//		xdoc.createPicture(blipId,
//				xdoc.getNextPicNameNumber(Document.PICTURE_TYPE_PNG), 90, 93, p);
//		pRun = getOrAddParagraphFirstRun(p, true, false);
//		setParagraphRunFontInfo(p, pRun, StringUtils.leftPad("D.", 10), "宋体",
//				"22");
//		blipId = p.getDocument().addPictureData(
//				new FileInputStream(new File("f:/saveFile/temp/image4.png")),
//				Document.PICTURE_TYPE_PNG);
//		xdoc.createPicture(blipId,
//				xdoc.getNextPicNameNumber(Document.PICTURE_TYPE_PNG), 90, 93, p);
//	}
}